import React, { useState, useEffect } from 'react';
import plcService from '../services/plcService';

const PLCVariableMonitor = () => {
  const [monitoredVariables, setMonitoredVariables] = useState([]);
  const [variableValues, setVariableValues] = useState({});
  const [isMonitoring, setIsMonitoring] = useState(false);
  const [newVariable, setNewVariable] = useState('');
  const [updateInterval, setUpdateInterval] = useState(1000);

  // 初始化监控变量列表
  useEffect(() => {
    // 默认监控的变量
    const defaultVariables = [
      'DB1,W0.0',  // 温度
      'DB1,W2.0',  // 湿度
      'DB1,W4.0',  // 货架状态
      'DB1,W6.0'   // 系统状态
    ];
    
    setMonitoredVariables(defaultVariables);
  }, []);

  // 处理变量值变化
  const handleVariableChange = (variable, newValue, oldValue) => {
    setVariableValues(prev => ({
      ...prev,
      [variable]: newValue
    }));
    
    // 在控制台输出变化信息
    console.log(`📊 ${variable} 变化: ${oldValue} → ${newValue}`);
  };

  // 启动监控
  const startMonitoring = () => {
    if (monitoredVariables.length === 0) {
      alert('请先添加要监控的变量');
      return;
    }
    
    plcService.startMonitoring(monitoredVariables, handleVariableChange, updateInterval);
    setIsMonitoring(true);
  };

  // 停止监控
  const stopMonitoring = () => {
    plcService.stopMonitoring();
    setIsMonitoring(false);
  };

  // 添加变量到监控列表
  const addVariable = () => {
    if (!newVariable.trim()) {
      alert('请输入变量名称');
      return;
    }
    
    if (!monitoredVariables.includes(newVariable)) {
      const updatedVariables = [...monitoredVariables, newVariable];
      setMonitoredVariables(updatedVariables);
      
      // 如果正在监控，动态添加新变量
      if (isMonitoring) {
        plcService.addMonitoringVariable(newVariable, handleVariableChange);
      }
    }
    
    setNewVariable('');
  };

  // 从监控列表中移除变量
  const removeVariable = (variableToRemove) => {
    const updatedVariables = monitoredVariables.filter(v => v !== variableToRemove);
    setMonitoredVariables(updatedVariables);
    
    // 更新显示的值
    setVariableValues(prev => {
      const newValues = { ...prev };
      delete newValues[variableToRemove];
      return newValues;
    });
    
    // 如果正在监控，动态移除变量
    if (isMonitoring) {
      plcService.removeMonitoringVariable(variableToRemove);
    }
  };

  // 变量描述映射
  const variableDescriptions = {
    'DB1,W0.0': '仓库温度 (°C)',
    'DB1,W2.0': '仓库湿度 (%)',
    'DB1,W4.0': '货架1状态',
    'DB1,W6.0': '系统运行状态'
  };

  return (
    <div style={{
      background: 'rgba(30, 30, 30, 0.9)',
      padding: '20px',
      borderRadius: '10px',
      border: '2px solid #2196F3',
      backdropFilter: 'blur(10px)',
      color: '#fff',
      maxWidth: '600px',
      margin: '20px auto'
    }}>
      <h2 style={{ textAlign: 'center', color: '#2196F3' }}>PLC变量持续监控</h2>
      
      {/* 控制面板 */}
      <div style={{ marginBottom: '20px', padding: '15px', background: '#2a2a2a', borderRadius: '5px' }}>
        <div style={{ display: 'flex', gap: '10px', alignItems: 'center', marginBottom: '10px' }}>
          <label>更新间隔 (ms):</label>
          <input
            type="number"
            value={updateInterval}
            onChange={(e) => setUpdateInterval(Number(e.target.value))}
            style={{ padding: '5px', width: '80px' }}
            min="100"
            max="10000"
          />
        </div>
        
        <div style={{ display: 'flex', gap: '10px' }}>
          <button
            onClick={startMonitoring}
            disabled={isMonitoring}
            style={{
              padding: '10px 15px',
              backgroundColor: isMonitoring ? '#666' : '#4CAF50',
              color: 'white',
              border: 'none',
              borderRadius: '5px',
              cursor: isMonitoring ? 'not-allowed' : 'pointer',
              fontWeight: 'bold'
            }}
          >
            {isMonitoring ? '监控中...' : '开始监控'}
          </button>
          
          <button
            onClick={stopMonitoring}
            disabled={!isMonitoring}
            style={{
              padding: '10px 15px',
              backgroundColor: !isMonitoring ? '#666' : '#f44336',
              color: 'white',
              border: 'none',
              borderRadius: '5px',
              cursor: !isMonitoring ? 'not-allowed' : 'pointer',
              fontWeight: 'bold'
            }}
          >
            停止监控
          </button>
        </div>
      </div>
      
      {/* 添加变量 */}
      <div style={{ marginBottom: '20px', padding: '15px', background: '#2a2a2a', borderRadius: '5px' }}>
        <h3>添加监控变量</h3>
        <div style={{ display: 'flex', gap: '10px' }}>
          <input
            type="text"
            value={newVariable}
            onChange={(e) => setNewVariable(e.target.value)}
            placeholder="输入PLC变量地址 (如: DB1,W0.0)"
            style={{ 
              padding: '8px', 
              flex: 1, 
              borderRadius: '5px',
              border: '1px solid #555',
              background: '#333',
              color: '#fff'
            }}
          />
          <button
            onClick={addVariable}
            style={{
              padding: '8px 15px',
              backgroundColor: '#2196F3',
              color: 'white',
              border: 'none',
              borderRadius: '5px',
              cursor: 'pointer',
              fontWeight: 'bold'
            }}
          >
            添加
          </button>
        </div>
      </div>
      
      {/* 监控变量列表 */}
      <div style={{ marginBottom: '20px' }}>
        <h3>监控变量列表</h3>
        {monitoredVariables.length === 0 ? (
          <p style={{ textAlign: 'center', color: '#888' }}>暂无监控变量</p>
        ) : (
          <ul style={{ 
            listStyle: 'none', 
            padding: 0, 
            maxHeight: '200px', 
            overflowY: 'auto',
            background: '#2a2a2a',
            borderRadius: '5px',
            padding: '10px'
          }}>
            {monitoredVariables.map((variable, index) => (
              <li 
                key={index} 
                style={{ 
                  display: 'flex', 
                  justifyContent: 'space-between', 
                  alignItems: 'center',
                  padding: '8px',
                  borderBottom: index < monitoredVariables.length - 1 ? '1px solid #444' : 'none'
                }}
              >
                <span>
                  <strong>{variableDescriptions[variable] || variable}</strong>
                  <br />
                  <small style={{ color: '#aaa' }}>{variable}</small>
                </span>
                <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
                  <span style={{ 
                    padding: '3px 8px', 
                    backgroundColor: '#444', 
                    borderRadius: '3px',
                    minWidth: '60px',
                    textAlign: 'center'
                  }}>
                    {variableValues[variable] !== undefined ? variableValues[variable] : '--'}
                  </span>
                  <button
                    onClick={() => removeVariable(variable)}
                    style={{
                      padding: '3px 8px',
                      backgroundColor: '#f44336',
                      color: 'white',
                      border: 'none',
                      borderRadius: '3px',
                      cursor: 'pointer'
                    }}
                  >
                    移除
                  </button>
                </div>
              </li>
            ))}
          </ul>
        )}
      </div>
      
      {/* 监控状态 */}
      <div style={{ 
        padding: '10px', 
        background: '#2a2a2a', 
        borderRadius: '5px',
        textAlign: 'center'
      }}>
        <p>
          监控状态: <strong style={{ color: isMonitoring ? '#4CAF50' : '#f44336' }}>
            {isMonitoring ? '运行中' : '已停止'}
          </strong>
          {' | '}
          监控变量数: <strong>{monitoredVariables.length}</strong>
          {' | '}
          更新间隔: <strong>{updateInterval}ms</strong>
        </p>
      </div>
    </div>
  );
};

export default PLCVariableMonitor;